package com.ruoyi.campus.controller;

import com.ruoyi.campus.domain.AlarmRecord;
import com.ruoyi.campus.service.IAlarmRecordService;
import com.ruoyi.campus.service.ISchoolInfoService;
import com.ruoyi.campus.websocket.AlarmWebSocketServer;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 小程序报警API控制器
 * 
 * @author campus-alarm
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/miniprogram/alarm")
public class MiniProgramAlarmController extends BaseController {

    @Autowired
    private IAlarmRecordService alarmRecordService;

    @Autowired
    private ISchoolInfoService schoolInfoService;

    /**
     * 提交报警信息
     */
    @PostMapping("/submit")
    @Log(title = "小程序提交报警", businessType = BusinessType.INSERT)
    public AjaxResult submitAlarm(@RequestBody Map<String, Object> alarmData) {
        try {
            Long userId = SecurityUtils.getUserId();
            
            // 创建报警记录
            AlarmRecord alarm = new AlarmRecord();
            alarm.setAlarmCode(generateAlarmCode());
            alarm.setAlarmType((Integer) alarmData.get("type"));
            alarm.setAlarmLevel((Integer) alarmData.get("level"));
            alarm.setAlarmTitle((String) alarmData.get("title"));
            alarm.setAlarmContent((String) alarmData.get("description"));
            alarm.setCreateBy(userId.toString());
            alarm.setCreateTime(DateUtils.getNowDate());
            
            // 处理位置信息
            if (alarmData.containsKey("location")) {
                Map<String, Object> location = (Map<String, Object>) alarmData.get("location");
                // 设置位置相关字段
            }
            
            int result = alarmRecordService.insertAlarmRecord(alarm);
            
            if (result > 0) {
                // 发送WebSocket通知
                Map<String, Object> notificationData = new HashMap<>();
                notificationData.put("type", "new_alarm");
                notificationData.put("alarmId", alarm.getAlarmId());
                notificationData.put("alarmCode", alarm.getAlarmCode());
                notificationData.put("level", alarm.getAlarmLevel());
                notificationData.put("timestamp", System.currentTimeMillis());
                
                AlarmWebSocketServer.broadcastAlarmMessage(notificationData);
                
                return AjaxResult.success("报警提交成功", alarm.getAlarmId());
            } else {
                return AjaxResult.error("报警提交失败");
            }
            
        } catch (Exception e) {
            logger.error("提交报警失败", e);
            return AjaxResult.error("提交报警失败：" + e.getMessage());
        }
    }

    /**
     * 上传单个文件
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // TODO: 实现文件上传逻辑
            return AjaxResult.success("文件上传成功", "file_url_here");
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传文件
     */
    @PostMapping("/uploadBatch")
    public AjaxResult uploadBatchFiles(@RequestParam("files") MultipartFile[] files) {
        try {
            List<String> fileUrls = new ArrayList<>();
            for (MultipartFile file : files) {
                // TODO: 实现批量文件上传逻辑
                fileUrls.add("file_url_here");
            }
            return AjaxResult.success("批量上传成功", fileUrls);
        } catch (Exception e) {
            logger.error("批量上传失败", e);
            return AjaxResult.error("批量上传失败：" + e.getMessage());
        }
    }

    /**
     * 查询报警历史
     */
    @GetMapping("/history")
    public TableDataInfo getAlarmHistory() {
        Long userId = SecurityUtils.getUserId();
        startPage();
        
        AlarmRecord queryAlarm = new AlarmRecord();
        // TODO: 根据用户ID查询相关报警记录
        List<AlarmRecord> list = alarmRecordService.selectAlarmRecordList(queryAlarm);
        
        return getDataTable(list);
    }

    /**
     * 获取报警详情
     */
    @GetMapping("/detail/{id}")
    public AjaxResult getAlarmDetail(@PathVariable("id") Long alarmId) {
        try {
            AlarmRecord alarm = alarmRecordService.selectAlarmRecordByAlarmId(alarmId);
            if (alarm == null) {
                return AjaxResult.error("报警记录不存在");
            }
            return AjaxResult.success(alarm);
        } catch (Exception e) {
            logger.error("获取报警详情失败", e);
            return AjaxResult.error("获取报警详情失败：" + e.getMessage());
        }
    }

    /**
     * 取消报警
     */
    @PostMapping("/cancel")
    public AjaxResult cancelAlarm(@RequestBody Map<String, Object> requestData) {
        try {
            Long alarmId = Long.valueOf(requestData.get("alarmId").toString());
            String reason = (String) requestData.get("reason");
            
            // TODO: 实现取消报警逻辑
            return AjaxResult.success("报警已取消");
        } catch (Exception e) {
            logger.error("取消报警失败", e);
            return AjaxResult.error("取消报警失败：" + e.getMessage());
        }
    }

    /**
     * 获取报警状态
     */
    @GetMapping("/status/{id}")
    public AjaxResult getAlarmStatus(@PathVariable("id") Long alarmId) {
        try {
            AlarmRecord alarm = alarmRecordService.selectAlarmRecordByAlarmId(alarmId);
            if (alarm == null) {
                return AjaxResult.error("报警记录不存在");
            }
            
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("alarmId", alarm.getAlarmId());
            statusInfo.put("status", alarm.getStatus());
            statusInfo.put("createTime", alarm.getCreateTime());
            statusInfo.put("updateTime", alarm.getUpdateTime());
            
            return AjaxResult.success(statusInfo);
        } catch (Exception e) {
            logger.error("获取报警状态失败", e);
            return AjaxResult.error("获取报警状态失败：" + e.getMessage());
        }
    }

    /**
     * 评价处理结果
     */
    @PostMapping("/rate")
    public AjaxResult rateAlarmResult(@RequestBody Map<String, Object> rateData) {
        try {
            Long alarmId = Long.valueOf(rateData.get("alarmId").toString());
            Integer rating = (Integer) rateData.get("rating");
            String comment = (String) rateData.get("comment");
            
            // TODO: 实现评价逻辑
            return AjaxResult.success("评价提交成功");
        } catch (Exception e) {
            logger.error("评价提交失败", e);
            return AjaxResult.error("评价提交失败：" + e.getMessage());
        }
    }

    /**
     * 获取报警类型
     */
    @GetMapping("/types")
    public AjaxResult getAlarmTypes() {
        List<Map<String, Object>> types = Arrays.asList(
            createAlarmType(1, "语言欺凌", "verbal_bullying"),
            createAlarmType(2, "身体暴力", "physical_violence"),
            createAlarmType(3, "网络欺凌", "cyber_bullying"),
            createAlarmType(4, "恶意玩笑", "malicious_joke"),
            createAlarmType(5, "其他", "other")
        );
        return AjaxResult.success(types);
    }

    /**
     * 获取紧急联系方式
     */
    @GetMapping("/emergency/{schoolId}")
    public AjaxResult getEmergencyContacts(@PathVariable("schoolId") Long schoolId) {
        try {
            // TODO: 根据学校ID查询紧急联系方式
            List<Map<String, Object>> contacts = new ArrayList<>();
            
            Map<String, Object> contact1 = new HashMap<>();
            contact1.put("name", "校园安全办公室");
            contact1.put("phone", "123-456-7890");
            contact1.put("type", "security");
            contacts.add(contact1);
            
            return AjaxResult.success(contacts);
        } catch (Exception e) {
            logger.error("获取紧急联系方式失败", e);
            return AjaxResult.error("获取紧急联系方式失败：" + e.getMessage());
        }
    }

    /**
     * 检查提交权限
     */
    @GetMapping("/checkSubmit")
    public AjaxResult checkSubmitPermission() {
        try {
            Long userId = SecurityUtils.getUserId();
            // TODO: 检查用户是否有提交报警的权限
            
            Map<String, Object> result = new HashMap<>();
            result.put("canSubmit", true);
            result.put("reason", "");
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("检查提交权限失败", e);
            return AjaxResult.error("检查权限失败：" + e.getMessage());
        }
    }

    /**
     * 用户统计数据
     */
    @GetMapping("/statistics")
    public AjaxResult getUserStatistics() {
        try {
            Long userId = SecurityUtils.getUserId();
            
            // TODO: 查询用户相关统计数据
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalAlarms", 0);
            statistics.put("pendingAlarms", 0);
            statistics.put("completedAlarms", 0);
            
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("获取用户统计数据失败", e);
            return AjaxResult.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取WebSocket客户端ID
     */
    @GetMapping("/wsClientId")
    public AjaxResult getWebSocketClientId() {
        try {
            Long userId = SecurityUtils.getUserId();
            String clientId = "miniprogram_" + userId + "_" + System.currentTimeMillis();
            return AjaxResult.success(clientId);
        } catch (Exception e) {
            logger.error("获取WebSocket客户端ID失败", e);
            return AjaxResult.error("获取客户端ID失败：" + e.getMessage());
        }
    }

    /**
     * 生成报警编号
     */
    private String generateAlarmCode() {
        return "AL" + DateUtils.dateTimeNow() + String.format("%04d", new Random().nextInt(10000));
    }

    /**
     * 创建报警类型对象
     */
    private Map<String, Object> createAlarmType(Integer id, String name, String code) {
        Map<String, Object> type = new HashMap<>();
        type.put("id", id);
        type.put("name", name);
        type.put("code", code);
        return type;
    }
} 